package com.party.mobile.task;

import com.party.common.utils.DateUtils;
import com.party.core.model.analysis.StatisticsUserVisit;
import com.party.core.service.analysis.IStatisticsUserService;
import com.party.core.service.analysis.IStatisticsUserVisitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户访问量统计的定时任务
 *
 * @author yuguangqing
 * @date 2018/9/12 0011
 * @time 下午 10:20
 */

@SuppressWarnings("all")
@Component(value = "quartzForUserVisit")
public class QuartzForUserVisit {

    @Autowired
    private IStatisticsUserService iStatisticsUserService;

    @Autowired
    private IStatisticsUserVisitService iStatisticsUserVisitService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 每天凌晨1点30分运行脚本统计前一天用户访问量的汇总数据
     */
    @Scheduled(cron = "0 30 1 * * ?")
    public void analysisUserVisit() {
        logger.info("用户访问量统计分析开始 《《《《《《《《《《《《《");
        Date queryDate = null;
        try {
            queryDate = DateUtils.yesterday();
//            queryDate = DateUtils.parse("2018-08-21", "yyyy-MM-dd");
        } catch (Exception e) {
            e.printStackTrace();
        }
        long startLongTime = System.currentTimeMillis();
        Map<String, Object> map = new HashMap<>();
        map.put("startDate", queryDate);
        map.put("endDate", DateUtils.addDay(queryDate,1));
        long queryStartTime = System.currentTimeMillis();
        map.put("userType", "new");
        StatisticsUserVisit newUserVisit =
                iStatisticsUserService.countNewAndOldUsersCount(map);//先查出当天的新用户
        map.put("userType", "old");
        StatisticsUserVisit oldUsesVisit =
                iStatisticsUserService.countNewAndOldUsersCount(map);//再查出当天的老用户
        //将后面查到的老用户数据量合并到新用户数据里，一起存放并插入到数据库中去
        newUserVisit.setCreateBy("system task");
        newUserVisit.setCreateDate(queryDate);
        newUserVisit.setUpdateDate(queryDate);
        newUserVisit.setOldNum(oldUsesVisit.getOldNum());
        long queryEndTime = System.currentTimeMillis();
        System.out.println(DateUtils.formatDate(queryDate) + "日共统计到 "
                + newUserVisit.getNewNum() + "个新用户，" + newUserVisit.getOldNum()
                + " 个老用户" + ",查询耗时：" + (queryEndTime - queryStartTime) + " ms");
        //以下插入当天的访问用户量的统计数据到tj_user_visit表中去
        iStatisticsUserVisitService.insert(newUserVisit);//此处的newUserVisit对象包含了 queryDate 当天的新老用户访问数据总量
        long taskEndTime = System.currentTimeMillis();
        System.out.println("插入任务共花费时间：" + (taskEndTime - queryEndTime) + " ms");
        System.out.println("当前任务共花费时间：" + (taskEndTime - startLongTime) + " ms");
        logger.info("用户访问量统计分析结束 《《《《《《《《《《《《《");
    }

}
